package sardine;

import io.netty.handler.codec.http.*;

import java.util.Objects;

/**
 * @auth bruce_sha
 * @date 2015/5/22
 */
public class Response {

    private HttpResponse response;
    private String body;

    protected Response() {
        // Used by wrapper
    }

    Response(HttpResponse response) {
        this.response = response;
    }


    /**
     * Sets the status code for the
     *
     * @param statusCode the status code
     */
    public void status(int statusCode) {
        //TODO:buru reson
        response.setStatus(new HttpResponseStatus(statusCode, ""));
//        response.setStatus(statusCode);
    }

    /**
     * Sets the content type for the response
     *
     * @param contentType the content type
     */
    public void contentType(String contentType) {
        //TODO:buru add 还是 set？
//        response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, Objects.requireNonNull(contentType));
//        response.setContentType(contentType);
    }

    /**
     * Sets the body
     *
     * @param body the body
     */
    public void body(String body) {
        this.body = body;
    }

    /**
     * returns the body
     *
     * @return the body
     */
    public String body() {
        return this.body;
    }

    /**
     * @return the raw response object handed in by Jetty
     */
    public HttpResponse raw() {
        return response;
    }

    /**
     * Trigger a browser redirect
     *
     * @param location Where to redirect
     */
    public void redirect(String location) {
        //scalatra 是 302
        redirect(location, HttpResponseStatus.FOUND.code());

//        if (LOG.isDebugEnabled()) {
//            LOG.debug("Redirecting ({} {} to {}", "Found", HttpServletResponse.SC_FOUND, location);
//        }
//        try {
//            response.sendRedirect(location);
//        } catch (IOException ioException) {
//            LOG.warn("Redirect failure", ioException);
//        }
        //TODO:buru
//        throw new RuntimeException();
    }

    /**
     * Trigger a browser redirect with specific http 3XX status code.
     *
     * @param location       Where to redirect permanently
     * @param httpStatusCode the http status code
     */
    public void redirect(String location, int httpStatusCode) {

        response.headers().set(HttpHeaderNames.LOCATION, location);

        response.setStatus(HttpResponseStatus.valueOf(httpStatusCode));

//        if (LOG.isDebugEnabled()) {
//            LOG.debug("Redirecting ({} to {}", httpStatusCode, location);
//        }
//        response.setStatus(httpStatusCode);
//        response.setHeader("Location", location);
//        response.setHeader("Connection", "close");
//        try {
//            response.sendError(httpStatusCode);
//        } catch (IOException e) {
//            LOG.warn("Exception when trying to redirect permanently", e);
//        }
        //TODO:buru
//        throw new RuntimeException();
    }

    /**
     * Adds/Sets a response header
     *
     * @param header the header
     * @param value  the value
     */
    public void header(CharSequence header, CharSequence value) {
        response.headers().add(header, value);
//        response.addHeader(header, value);
    }

    public void headerInt(CharSequence header, int value) {
        response.headers().addInt(header, value);
//        response.addHeader(header, value);
    }


    /**
     * Adds not persistent cookie to the response.
     * Can be invoked multiple times to insert more than one cookie.
     *
     * @param name  name of the cookie
     * @param value value of the cookie
     */
    public void cookie(String name, String value) {
        cookie(name, value, -1, false);
    }

    /**
     * Adds cookie to the response. Can be invoked multiple times to insert more than one cookie.
     *
     * @param name   name of the cookie
     * @param value  value of the cookie
     * @param maxAge max age of the cookie in seconds (negative for the not persistent cookie,
     *               zero - deletes the cookie)
     */
    public void cookie(String name, String value, long maxAge) {
        cookie(name, value, maxAge, false);
    }

    /**
     * Adds cookie to the response. Can be invoked multiple times to insert more than one cookie.
     *
     * @param name    name of the cookie
     * @param value   value of the cookie
     * @param maxAge  max age of the cookie in seconds (negative for the not persistent cookie, zero - deletes the cookie)
     * @param secured if true : cookie will be secured
     *                zero - deletes the cookie)
     */
    public void cookie(String name, String value, long maxAge, boolean secured) {
        cookie("", name, value, maxAge, secured);
    }

    /**
     * Adds cookie to the response. Can be invoked multiple times to insert more than one cookie.
     *
     * @param path    path of the cookie
     * @param name    name of the cookie
     * @param value   value of the cookie
     * @param maxAge  max age of the cookie in seconds (negative for the not persistent cookie, zero - deletes the cookie)
     * @param secured if true : cookie will be secured
     *                zero - deletes the cookie)
     */
    public void cookie(String path, String name, String value, long maxAge, boolean secured) {
        Cookie cookie = new DefaultCookie(name, value);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        cookie.setSecure(secured);

        response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode(cookie));

//        Cookie cookie = new Cookie(name, value);
//        cookie.setPath(path);
//        cookie.setMaxAge(SECURITY_MAX_AGE);
//        cookie.setSecure(secured);
//        response.addCookie(cookie);

        //TODO:buru
//        throw new RuntimeException();
    }

    /**
     * Removes the cookie.
     *
     * @param name name of the cookie
     */
    public void removeCookie(String name) {

        Cookie cookie = new DefaultCookie(name, "");
//        cookie.setPath(path);
        cookie.setMaxAge(0);
//        cookie.setSecure(secured);

        response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode(cookie));


//        Cookie cookie = new Cookie(name, "");
//        cookie.setMaxAge(0);
//        response.addCookie(cookie);
//        TODO:buru
//        throw new RuntimeException();
    }

    //TODO：直接转向文件
    public void file(String filePath) {
//        get("/home", (req, res) -> {
//            byte[] encoded = java.nio.file.Files.readAllBytes(Paths.get(path));
//            String s = new String(encoded, Charset.defaultCharset());
//            return s;
//        });
    }
}
